package keter.ssh;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import keter.framework.AbstractBaseSSHConfig;
import keter.framework.util.IOUtil;
import keter.ssh.cli.CommandOptions;
import keter.ssh.exec.Executor;
import keter.ssh.hosts.Fetcher;
import keter.ssh.hosts.SimpleFetcher;

public class SshBatchMain extends AbstractBaseSSHConfig{

	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(SshBatchMain.class);
	
	Fetcher fetcher;
	
	public SshBatchMain(){
		fetcher = new SimpleFetcher();
	}
	
	public static void main(String[] args) throws Exception{
		System.out.println(SshBatchMain.class.getClassLoader().getResource("."));
		useConfig("hosts.properties");
		CommandOptions cmder = new CommandOptions();
		CommandLineParser parser = new DefaultParser(); 
		CommandLine cmd = parser.parse(cmder.getOptions(), args); 
		if(cmd.hasOption("h")) { 
		   // 这里显示简短的帮助信息
		   System.out.println("我是帮助： \n"
		   		+ " -put:文件上传\n "
		   		+ " -get src dest:文件下载,远程文件URI 本地目录"
		        + " -put src dest:文件上传,本地文件URI 远程目录");
		   System.exit(0);
		}
		
		SshBatchMain sb = new SshBatchMain();
		Executor.init(sb.fetcher.getHosts(SshBatchMain.prop),prop.getInt("thread"));
		//只有一个参数:直接执行命令
		if(args.length==1) { 
			logger.info("执行命令:{}",args[0]);
			Executor.execute(args[0]);
		}
		
		if(cmd.hasOption("get")) { 
			String[] params = cmd.getOptionValues("get"); 
			String src = params[0];
			String dest = params[1];
			IOUtil.ensureExists(dest);
			Executor.downloadToEachFolder(src, dest);
		}
		
		//单线程执行后退出
		if(prop.getInt("thread")==1){
			System.exit(0);
		}
	}
}
